package net.luoran.dvm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.luoran.dvm.common.base.PageFactory;
import net.luoran.dvm.common.base.Result;
import net.luoran.dvm.common.util.FileUtil;
import net.luoran.dvm.entity.ElementDO;
import net.luoran.dvm.entity.ElementGroupDO;
import net.luoran.dvm.entity.SysFileDO;
import net.luoran.dvm.entity.dto.ElementDTO;
import net.luoran.dvm.entity.dto.ElementGroupDTO;
import net.luoran.dvm.service.ElementGroupService;
import net.luoran.dvm.service.ElementService;
import net.luoran.dvm.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 数据元素分组 前端控制器
 * </p>
 *
 * @author MyBatisPlusGenerater
 * @since 2020-10-29
 */
@Controller
@RequestMapping("/element")
public class ElementGroupController {

    @Value("${server.servlet.context-path}")
    public String contextPath;

    @Value("${upload.file.path}")
    public String basePath;

    @Autowired()
    public ElementGroupService elementGroupService;

    @Autowired()
    public ElementService elementService;

    @Autowired
    public SysFileService sysFileService;

    @GetMapping
    public String panelMain(Model model) {
        model.addAttribute("contextPath", contextPath);
        return "element";
    }

    /**
     * 查询展示
     *
     * @param elementGroupDTO
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public Result showList(@RequestBody ElementGroupDTO elementGroupDTO) {
        Result result = Result.ok();
        try {
            QueryWrapper<ElementGroupDO> queryWrapper = new QueryWrapper();
            if (StringUtils.isNotBlank(elementGroupDTO.getGroupName())) {
                queryWrapper.like("group_name", elementGroupDTO.getGroupName());
            }
            queryWrapper.orderByAsc("order_number");
            Page<ElementGroupDO> page = elementGroupService.page(PageFactory.createPageInfo(elementGroupDTO.getCurrent(), elementGroupDTO.getSize()), queryWrapper);
            result.setData(page);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 批量删除group的信息
     *
     * @param groupId
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(@RequestBody List<Integer> groupId) {
        Result result = Result.ok();
        try {
            if (groupId.size() > 0) {
                for (Integer id : groupId) {
                    ElementGroupDO oldElementGroup = elementGroupService.getById(id);
                    //删除文件
                    SysFileDO fileDO = sysFileService.getById(oldElementGroup.getFileId());
                    FileUtil.deleteFile(fileDO);
                    //移除信息
                    sysFileService.removeByFileId(fileDO.getFileId());
                    //移除外表信息
                    QueryWrapper<ElementDO> elementDOQueryWrapper = new QueryWrapper<>();
                    elementDOQueryWrapper.eq("group_id", oldElementGroup.getGroupId());

                    List<ElementDO> elementDOList = elementService.list(elementDOQueryWrapper);
                    if (elementDOList.size() < 0) {
                        return Result.error("数据不存在");
                    }
                    for (ElementDO elementDO : elementDOList) {
                        sysFileService.removeByFileId(elementDO.getFileId());
                        elementService.removeByElementId(elementDO.getElementId());
                        SysFileDO elementFile = sysFileService.getById(elementDO.getFileId());
                        FileUtil.deleteFile(elementFile);
                    }
                    //移除 ElementGroup 的文件信息
                    sysFileService.removeByFileId(oldElementGroup.getFileId());
                }
                elementGroupService.removeByGroupIds(groupId);
            } else {
                return Result.error("不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 上传图片
     *
     * @param
     * @return
     */
    @PostMapping("/uploadData")
    @ResponseBody
    public Result fileUpload(String operation, ElementGroupDO elementGroup, String fileId) {
        Result result = Result.ok();
        try {
            StringBuffer data = new StringBuffer();
            data.append("上传成功。\n");

            //依据 fileId 查询出信息
            SysFileDO oldFile = sysFileService.getById(fileId);
            if (oldFile == null) {
                result = Result.error("该数据不存在");
                return result;
            }

            if ("insert".equals(operation)) {
                //数据元素分组表
                elementGroup.setFileUrl(oldFile.getFileUrl());
                elementGroup.setFileId(oldFile.getFileId());
                elementGroupService.saveElementGroup(elementGroup);
            } else {
                //修改 elementGroup 表的信息
                ElementGroupDO oldElementGroupDO = elementGroupService.getById(elementGroup.getGroupId());
                oldElementGroupDO.setFileUrl(oldFile.getFileUrl());
                oldElementGroupDO.setUpdateTime(LocalDateTime.now());
                oldElementGroupDO.setGroupName(elementGroup.getGroupName());
                oldElementGroupDO.setOrderNumber(elementGroup.getOrderNumber());
                elementGroupService.saveOrUpdateElementGroupDO(oldElementGroupDO);
            }
            result.setData(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误,请重新上传");
        }
        return result;
    }

    /**
     * 查询元素详细展示
     *
     * @param
     * @return
     */
    @PostMapping("/query")
    @ResponseBody
    public Result query(@RequestBody ElementDTO elementDTO) {
        Result result = Result.ok();
        try {
            QueryWrapper<ElementDO> queryWrapper = new QueryWrapper();
            queryWrapper.eq("group_id", elementDTO.getGroupId());
            if (StringUtils.isNotBlank(elementDTO.getElementName())) {
                queryWrapper.like("element_name", elementDTO.getElementName());
            }
            Page<ElementDO> page = elementService.page(PageFactory.createPageInfo(elementDTO.getCurrent(), elementDTO.getSize()), queryWrapper);
            result.setData(page);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 删除 Element
     *
     * @param elementId
     * @return
     */
    @PostMapping("/deleteElement")
    @ResponseBody
    public Result deleteElement(String elementId) {
        Result result = Result.ok();
        try {
            if (elementId != null) {
                //删除文件 先查出fileId
                ElementDO elementDO = elementService.getById(elementId);
                SysFileDO fileDO = sysFileService.getById(elementDO.getFileId());
                sysFileService.removeByFileId(elementDO.getFileId());
                elementService.removeByElementId(elementDO.getElementId());
                FileUtil.deleteFile(fileDO);
            } else {
                return Result.error("不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 上传图片元素数据
     *
     * @return
     */
    @PostMapping("/uploadElementData")
    @ResponseBody
    public Result uploadElementData(ElementDO element, String operation, String fileId) {
        Result result = Result.ok();
        try {
            StringBuffer data = new StringBuffer();
            data.append("上传成功。\n");

            //依据 fileId 查询出信息
            SysFileDO oldFile = sysFileService.getById(fileId);
            if (oldFile == null) {
                result = Result.error("该数据不存在");
                return result;
            }

            if ("insert".equals(operation)) {
                //把file_id和状态存入 大屏元素表
                ElementDO newElement = new ElementDO();
                newElement.setGroupId(element.getGroupId());
                newElement.setFileUrl(oldFile.getFileUrl());
                newElement.setFileId(oldFile.getFileId());
                newElement.setElementName(element.getElementName());
                newElement.setConfigJson(element.getConfigJson());
                elementService.saveElement(newElement);
            } else {
                //修改 element 表的信息
                ElementDO oldElementDO = elementService.getById(element.getElementId());
                oldElementDO.setElementName(element.getElementName());
                oldElementDO.setConfigJson(element.getConfigJson());
                oldElementDO.setFileUrl(oldFile.getFileUrl());
                elementService.saveOrUpdateElement(oldElementDO);
            }
            result.setData(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误,请重新上传");
        }
        return result;
    }

    /**
     * 前台查询展示
     *
     * @param elementGroupDTO
     * @return
     */
    @PostMapping("/queryAll")
    @ResponseBody
    public Result queryAll(ElementGroupDTO elementGroupDTO) {
        Result result = Result.ok();
        try {
            QueryWrapper<ElementGroupDO> queryWrapper = new QueryWrapper();
            if (StringUtils.isNotBlank(elementGroupDTO.getGroupName())) {
                queryWrapper.like("group_name", elementGroupDTO.getGroupName());
            }
            queryWrapper.orderByAsc("order_number");
            List<ElementGroupDO> listElementGroup = elementGroupService.list(queryWrapper);

            //通过  ElementGroup 的 groupid 查询 element 里面的数据
            for (ElementGroupDO elementGroup : listElementGroup) {
                QueryWrapper<ElementDO> queryElement = new QueryWrapper();
                queryElement.eq("group_id", elementGroup.getGroupId());
                List<ElementDO> elementDOList = elementService.list(queryElement);
                elementGroup.setChildren(elementDOList);
            }
            result.setData(listElementGroup);

        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

}
